import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import {
  getRestaurantListAPI,
  DataType,
  GetDishPage,
  updateStatusAPI,
  CreateRestaurant,
  createRestaurantAPI,
  getRestaurantListsAPI,
} from '@/service/restaurant';
import FormItem from 'antd/es/form/FormItem';

const queryPage: GetDishPage = {
  name: '',
  current: 1,
  size: 10,
  masterId: 0,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const masterId = localStorage.getItem('masterId');
  queryPage.masterId = masterId == null ? 0 : Number(masterId);

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '店铺名称',
        dataIndex: 'name',
        sorter: true,
        render: (name) => `${name}`,
        width: '15%',
      },
      {
        title: '地址',
        dataIndex: 'address',
        render: (classify) => `${classify}`,
        width: '10%',
      },
      {
        title: '评分',
        dataIndex: 'score',
        sorter: true,
        render: (number) => `${number} 分`,
        width: '10%',
      },
      {
        title: '操作',
        width: '15%',
        render: (_, record) => (
          <>
            <Button
              onClick={() => {
                debugger;
                updateStatusAPI(record.id);
              }}
            >
              {record.state === 0 ? '恢复' : '停用'}
            </Button>
          </>
        ),
      },
    ],
    [],
  );

  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    try {
      const res = await getRestaurantListsAPI(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );

  //搜索
  const onSearch = useCallback(
    (value: string) => {
      queryPage.name = value;
      handleTableChange();
    },
    [handleTableChange],
  );

  const [form] = Form.useForm();
  const onFinish = async (values: CreateRestaurant) => {
    const id = localStorage.getItem('restaurant');
    const seat = {
      restaurantName: values.restaurantName,
      restaurantAddress: values.restaurantAddress,
      phone: values.phone,
    };
    await createRestaurantAPI(seat);

    fetchData();
  };
  const addSeat = () => {
    Modal.confirm({
      title: '新增餐厅',
      //from表单
      content: (
        <Form form={form} name="basic" onFinish={onFinish}>
          <FormItem
            label="店铺名称"
            name="restaurantName"
            rules={[{ required: true, message: '请输入店铺位名称' }]}
          >
            <Input />
          </FormItem>
          <FormItem
            label="店铺地址"
            name="restaurantAddress"
            rules={[{ required: true, message: '请输入店铺地址' }]}
          >
            <Input />
          </FormItem>
          <FormItem
            label="管理员手机号"
            name="phone"
            rules={[{ required: true, message: '请输入店铺管理员' }]}
          >
            <Input />
          </FormItem>
        </Form>
      ),
      onOk: () => {
        form.submit();
      },
    });
  };

  return (
    <div>
      <Button onClick={addSeat}>新增店铺</Button>

      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        onChange={handleTableChange}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};
export default App;
